package com.hkts.naturalgasauthentication.security.validate;

import cn.hutool.core.util.StrUtil;
import com.hkts.naturalgasauthentication.base.entity.HontUser;
import com.hkts.naturalgasauthentication.base.service.HontUserService;
import com.hkts.naturalgasauthentication.common.Exception.LoginFailLimitException;
import com.hkts.naturalgasauthentication.security.SecurityUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component("mobileUserDetailsService")
public class MobileUserDetilsService implements UserDetailsService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HontUserService userService;

    @Override
    public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
        log.info("请求的手机号是：" + mobile);
        String flagKey = "loginFailFlag:"+mobile;
        String value = redisTemplate.opsForValue().get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if(StrUtil.isNotBlank(value)){
            //超过限制次数
            throw new LoginFailLimitException("登录错误次数超过限制，请"+timeRest+"分钟后再试");
        }
       //User user=userService.findByMobile(mobile);
        HontUser user= userService.cutomerfindByMobile(mobile);
        return new SecurityUserDetails(user);
    }
}
